﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Resources;
using System.Windows.Threading;

namespace cameraforhtml
{
    public partial class MainPage : PhoneApplicationPage
    {

        private DispatcherTimer _timer = null;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            SaveFilesToIsoStore();
            webBrowser.ScriptNotify += new EventHandler<NotifyEventArgs>(webBrowser_ScriptNotify);
        }

        override protected void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            webBrowser.Navigate(new Uri("html_content/index.html", UriKind.Relative));
        }

        void webBrowser_ScriptNotify(object sender, NotifyEventArgs e)
        {
            string val = e.Value;
            System.Diagnostics.Debug.WriteLine(val);
        }

        private void SaveFilesToIsoStore()
        {
            //These files must match what is included in the application package,
            //or BinaryStream.Dispose below will throw an exception.
            string[] files = {
            "html_content/index.html",
            "html_content/script.js",
            "html_content/default.png"
            };

            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            foreach (string f in files)
            {
                StreamResourceInfo sr = Application.GetResourceStream(new Uri(f, UriKind.Relative));
                using (BinaryReader br = new BinaryReader(sr.Stream))
                {
                    byte[] data = br.ReadBytes((int)sr.Stream.Length);
                    SaveToIsoStore(f, data);
                }
            }
        }

        private void SaveToIsoStore(string fileName, byte[] data)
        {
            string strBaseDir = string.Empty;
            string delimStr = "/";
            char[] delimiter = delimStr.ToCharArray();
            string[] dirsPath = fileName.Split(delimiter);

            //Get the IsoStore.
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

            //Re-create the directory structure.
            for (int i = 0; i < dirsPath.Length - 1; i++)
            {
                strBaseDir = System.IO.Path.Combine(strBaseDir, dirsPath[i]);
                isoStore.CreateDirectory(strBaseDir);
            }

            //Remove the existing file.
            if (isoStore.FileExists(fileName))
            {
                isoStore.DeleteFile(fileName);
            }

            //Write the file.
            using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(fileName)))
            {
                bw.Write(data);
                bw.Close();
            }
        }

        private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (this.CameraViewfinder.Visibility == System.Windows.Visibility.Visible)
            {
                this.CameraViewfinder.CaptureImage();
                this.CameraViewfinder.Visibility = System.Windows.Visibility.Collapsed;

                if (_timer == null)
                {
                    _timer = new DispatcherTimer();
                    _timer.Interval = new TimeSpan(0, 0, 0, 0, 3000);
                    _timer.Tick += new EventHandler(AlertShowingTimer_Tick);
                }
                _timer.Stop();
                _timer.Start();
            }
            else
            {
                webBrowser.InvokeScript("resetImage", new String[] {});
                this.CameraViewfinder.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void AlertShowingTimer_Tick(object sender, EventArgs e)
        {
            (sender as DispatcherTimer).Stop();
            webBrowser.InvokeScript("reloadImage", new String[] { "capturedimage.jpg" });
        }

    }
}